﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;

using PLCS.App.Events;
using PLCS.App.Shared.Extensions;
using PLCS.App.Shared.Models;
using PLCS.App.Shared.ViewModels;
using PLCS.App.Shared.Views.Common;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.UserApp.Dtos;
using PLCS.Client.IService.LogManager;
using PLCS.Client.IService.UserAuthorization;
using PLCS.Shared.Common.Constant;

using System.Windows.Controls;

namespace PLCS.App.ViewModels;

public class LoginViewModel : BaseViewModel, IDialogAware
{
    private UserRegisterDto _resgiterModel = new UserRegisterDto();
    private readonly IEventAggregator _aggregator;
    private readonly ILogger<LoginViewModel> _logger;
    private readonly IUserService _userService;
    private bool _isLoginDialog;
    private UserControl _loginDialogContext;
    private int _selectIndex;
    private string _userName;
    private string _passWord;
    private string _error;
    private bool _isActive;

    #region IDialogAware

    public string Title => "登录";

    public event Action<IDialogResult> RequestClose;

    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
    }

    #endregion IDialogAware

    public bool IsLoginDialog
    {
        get { return _isLoginDialog; }
        set { SetProperty(ref _isLoginDialog, value); }
    }

    public UserControl LoginDialogContext
    {
        get { return _loginDialogContext; }
        set { SetProperty(ref _loginDialogContext, value); }
    }

    public int SelectIndex
    {
        get { return _selectIndex; }
        set { _selectIndex = value; RaisePropertyChanged(); }
    }

    public string UserName
    {
        get { return _userName; }
        set { _userName = value; RaisePropertyChanged(); }
    }

    public string PassWord
    {
        get { return _passWord; }
        set { _passWord = value; RaisePropertyChanged(); }
    }

    public string Error
    {
        get { return _error; }
        set { _error = value; RaisePropertyChanged(); }
    }

    public bool IsActive
    {
        get { return _isActive; }
        set { _isActive = value; RaisePropertyChanged(); }
    }

    public UserRegisterDto ResgiterModel
    {
        get { return _resgiterModel; }
        set { SetProperty(ref _resgiterModel, value); }
    }

    public DelegateCommand<object> ChangePageCommand { get; }
    public DelegateCommand LoginCommand { get; }
    public DelegateCommand CloseMessageCommand { get; }
    public DelegateCommand ResgiterCommand { get; }
    public DelegateCommand<Window> CloseCommand { get; }

    public LoginViewModel(IEventAggregator aggregator, ILogger<LoginViewModel> logger, IUserService userService)
    {
        _aggregator = aggregator;
        _logger = logger;
        _userService = userService;
        View = "登录界面";
        UserName = "admin";
        PassWord = "123456";
        ChangePageCommand = new DelegateCommand<object>(ChangePage);
        LoginCommand = new DelegateCommand(Login);
        CloseMessageCommand = new DelegateCommand(CloseMessage);
        ResgiterCommand = new DelegateCommand(Resgiter);
        CloseCommand = new DelegateCommand<Window>(Close);
    }

    private void Close(Window w)
    {
        w.Close();
        Environment.Exit(0);
    }

    /// <summary>
    /// 注册
    /// </summary>
    private async void Resgiter()
    {
        try
        {
            LoadLoginDialog(true);
            await _userService.ResgiterAsync(ResgiterModel);
            Error = "注册成功"; IsActive = true; return;
        }
        catch (Exception ex)
        {
            Error = ex.Message; IsActive = true; return;
        }
        finally
        {
            Log("注册", ResgiterModel);
            LoadLoginDialog(false);
        }
    }

    private void CloseMessage()
    {
        IsActive = false;
    }

    /// <summary>
    /// 切换注册/登录
    /// </summary>
    /// <param name="obj"></param>
    private void ChangePage(object obj)
    {
        SelectIndex = int.Parse(obj.ToString());
    }

    /// <summary>
    /// 登录
    /// </summary>
    private async void Login()
    {
        try
        {
            LoadLoginDialog(true);
            _logger.LogInformation("开始登录");
            UserLoginDto userLoginDto = new UserLoginDto()
            {
                UserName = UserName,
                Password = PassWord
            };
            var user = await _userService.LoginAsync(userLoginDto);
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            GlobalVariable.CurrentUser = user;
            User.Username = UserName;
            _aggregator.GetEvent<MenuEvent>().Publish(user.Menus.ToObservable());
            Log("登录", new { Object = UserName });
        }
        catch (Exception ex)
        {
            Error = ex.Message; IsActive = true; return;
        }
        finally
        {
            LoadLoginDialog(false);
        }
    }

    public void LoadLoginDialog(bool res)
    {
        IsLoginDialog = res;
        if (IsLoginDialog)
            LoginDialogContext = new ProgressView();
    }
}